#! /usr/bin/python

import sys
import os
import argparse

from Scenario import Scenario

from errors import *
from events import *

class Engine(object):
    def __init__(self):
        self.scenario = None
        self.parser = argparse.ArgumentParser(
                                           description='Play a text adventure!')
        self.customizeParser()

        if len(sys.argv) == 1:
            sys.argv.append('')

        self.args = self.parser.parse_args(sys.argv[1:])


    def customizeParser(self):
        self.parser.add_argument('scenarioDir',
                                    default='',
                                    metavar='scenarioDirectory',
                                    type=str,
                                    help='The path to the directory that contai'
                                         'ns the adventure you want to play.')
        

    def play(self):
        scenePath = self.args.scenarioDir

        while not self.scenario:
            try:
                if scenePath:
                    scenario = self.scenario = Scenario(scenePath)
                else:
                    scenario = self.scenario = Scenario(self.getScenarioDir())
            except ScenarioNotFoundError as snfe:
                print(snfe)
                scenePath = None
            except ExitEvent as ee:
                ee()

        self.showOutput( self.scenario.getWelcomeText() )
        self.getInput()

        while True:
            try:
                if scenario.state == scenario.STATE_INITIALIZING:
                    scenario.setState(scenario.STATE_PLAYING)
                elif scenario.state == scenario.STATE_PLAYING:
                    scenario.processInput(self.getInput())
                elif scenario.state == scenario.STATE_LOSS:
                    scenario.lose()
                elif scenario.state == scenario.STATE_WIN:
                    scenario.win()
            except TABaseThrowable as tabt:
                self.handleThrowable(tabt)


    def showOutput(self, output, newLine='\n'):
        sys.stdout.write(output + newLine)                


    def getInput(self, prompt=''):
        return raw_input(prompt + '>  ')
        

    def handleThrowable(self, throwable):
        if callable(throwable):
            throwable()


    def getScenarioDir(self):
        return self.getInput('''You didn't specify a scenario to play.  Please'''
                         ''' enter the path to a scenario folder, or type'''
                         ''' "quit".\n''')


if __name__ == '__main__':
    e = Engine()
    e.play()
